package com.cygsunri.consumption.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cygsunri.common.service.CommonDataService;
import com.cygsunri.consumption.entity.Branch;
import com.cygsunri.consumption.entity.request.AnalysisRequest;
import com.cygsunri.consumption.entity.request.NewAnalysisRequest;
import com.cygsunri.consumption.service.BranchService;
import com.cygsunri.consumption.service.ConsumptionAnalysisService;
import com.cygsunri.measurement.entity.Flag;
import com.cygsunri.measurement.entity.MeasurementValue;
import com.cygsunri.util.DateUtil;
import com.cygsunri.util.TimeUtil;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.axis.CategoryAxis;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 能耗分析API
 */
@RestController
@RequestMapping("/api/consumption/analysis")
public class ConsumptionAnalysisController {

    @Autowired
    private BranchService branchService;

    @Autowired
    private CommonDataService commonDataService;

    @Autowired
    private ConsumptionAnalysisService consumptionAnalysisService;

    /**
     * 同比分析（旧，已废弃）
     */
    @RequestMapping(value = "/data", method = RequestMethod.POST)
    public ResponseEntity<List<Map>> getConsumptionAnalysis(@RequestBody AnalysisRequest analysisRequest) {
        List<Map> list = new ArrayList<>();
        List<Branch> branches = new ArrayList<>();
        String pageType = analysisRequest.getPageType();
        switch (pageType) {
            case "branch":
                branches = branchService.getBranchesByBranchAndEnergySort(analysisRequest.getId(), analysisRequest.getEnergySort());
                break;
            case "department":
                break;
            case "area":
                break;
            case "item":
                branches = branchService.getBranchesByBuildingAndEnergyItem(analysisRequest.getBuildingId(), analysisRequest.getId());
                break;
            case "building":
                //需要考虑，分支上下级
                branches = branchService.getBranchesHasPsrIDByBuildingAndEnergySort(analysisRequest.getId(), analysisRequest.getEnergySort());
                break;
            default:
                return null;
        }

        LocalDateTime l = DateUtil.parse(analysisRequest.getYear());
        for (int i = 1; i <= 12; i++) {
            l = l.withMonth(i);

            Map<String, Double> map = new HashMap<>();
            long select = TimeUtil.toMilliSeconds(l);
            long last = TimeUtil.toMilliSeconds(l.minusYears(1));
            Double selectV = 0d, lastV = 0d;
            for (Branch branch : branches) {
                String psrID = branch.getPsrID();
                if (StringUtils.isBlank(psrID)) {
                    continue;
                }

                if (LocalDateTime.now().compareTo(l) >= 0) {
                    MeasurementValue selectYear = commonDataService.getValue(psrID, analysisRequest.getEnergySort(), select, 502);
                    selectV += selectYear.isInValid() ? 0d : selectYear.getData();
                }

                MeasurementValue lastYear = commonDataService.getValue(psrID, analysisRequest.getEnergySort(), last, 502);
                lastV += lastYear.isInValid() ? 0d : lastYear.getData();
            }
            map.put("currentYear", LocalDateTime.now().compareTo(l) >= 0 ? selectV : null);
            map.put("lastYear", lastV);
            list.add(map);
        }

        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    /**
     * 能耗分析图表
     */
    @RequestMapping(value = "/datas", method = RequestMethod.POST)
    public ResponseEntity<String> consumptionAnalysis(@RequestBody @Valid NewAnalysisRequest newAnalysisRequest) {
        Option option = new Option();
        CategoryAxis categoryAxis = new CategoryAxis();
        option.xAxis(categoryAxis);
        List<String> times = new ArrayList<>();
        int flag;
        switch (newAnalysisRequest.getDateType()) {
            case "day":
                times = DateUtil.getHours(newAnalysisRequest.getDateValue());
                times.remove(0);
                flag = Flag.HOUR_DIFF;
                break;
            case "month":
                times = DateUtil.getDays(newAnalysisRequest.getDateValue());
                flag = Flag.DAY_DIFF;
                break;
            case "year":
                times = DateUtil.getMonths(newAnalysisRequest.getDateValue());
                flag = Flag.MONTH_DIFF;
                break;
            default:
                return null;
        }
        switch (newAnalysisRequest.getCategory()) {
            case "branch":
                option = consumptionAnalysisService.getBranchAnalysis(option, newAnalysisRequest, times, flag);
                break;
            case "item":
                option = consumptionAnalysisService.getItemAnalysis(option, newAnalysisRequest, times, flag);
                break;
            case "building":
                option = consumptionAnalysisService.getBuildingAnalysis(option, newAnalysisRequest, times, flag);
                break;
            default:
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(JSON.toJSONString(option), HttpStatus.OK);
    }

    /**
     * 能耗分析表格
     */
    @RequestMapping(value = "/datas/without/hierarchy", method = RequestMethod.POST)
    public ResponseEntity<String> consumptionAnalysisTable(@RequestBody NewAnalysisRequest newAnalysisRequest) {
        JSONArray jsonArray = new JSONArray();
        List<String> times = new ArrayList<>();
        int flag;
        switch (newAnalysisRequest.getDateType()) {
            case "day":
                times = DateUtil.getHours(newAnalysisRequest.getDateValue());
                times.remove(0);
                flag = Flag.HOUR_DIFF;
                break;
            case "month":
                times = DateUtil.getDays(newAnalysisRequest.getDateValue());
                flag = Flag.DAY_DIFF;
                break;
            case "year":
                times = DateUtil.getMonths(newAnalysisRequest.getDateValue());
                flag = Flag.MONTH_DIFF;
                break;
            default:
                return null;
        }
        switch (newAnalysisRequest.getCategory()) {
            case "branch":
                jsonArray = consumptionAnalysisService.getBranchAnalysisTable(jsonArray, newAnalysisRequest, times, flag);
                break;
            case "item":
                jsonArray = consumptionAnalysisService.getItemAnalysisTable(jsonArray, newAnalysisRequest, times, flag);
                break;
            case "building":
                jsonArray = consumptionAnalysisService.getBuildingAnalysisTable(jsonArray, newAnalysisRequest, times, flag);
                break;
            default:
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(JSON.toJSONString(jsonArray), HttpStatus.OK);
    }
}
